const { readFile } = require("fs/promises");
const path = require("path");
const express = require("express");
const router = express.Router();
const db = require("../db");
// const articleImgDir = path.join(__dirname, "../public/articleImg");
// 获取文章列表
router.get("/getArticleList", (req, res) => { 
    const SQLstr = "SELECT id,img,title,pubLishTime,views,tags,summary FROM article";
    db.query(SQLstr,(err,result)=>{
        if(err){
            return res.send({
                status:400,
                data:{message:"查询失败"}
            })
        }
        res.send({
            status:200,
            data:{
                message:"查询成功",
                list:result
            }
        })
    })
    
})
// const baseURL = "http://localhost:3000/";
// 获取文章详情
router.get("/getArticleDetail", async (req, res) => {
    const id = req.query.id;
    const filePath = path.join(__dirname, "../public/markdown", id + ".md");

    try {
        const content = await readFile(filePath, "utf-8");
      res.type("text/plain").send({
        status: 200,
        data: {
            message: "查询成功",
            content: content,
        },
      });
    } catch (e) {
      res.status(404).json({ msg: "Markdown 文件不存在",url:filePath });
    }
})

// 增加views
router.post('/addViewsForArticle', (req, res) => {
    const id = req.body.id;
    console.log(id);
    
    if (!id) {
        return res.send({   
            status: 400, 
            data: { message: '文章ID不能为空' } 
        });
    }
    const sql = 'UPDATE article SET views = views + 1 WHERE id = ?';
    db.query(sql, [id], (err, results) => {
        if (err) {
            return res.send({ 
                status: 400, 
                data: { message: '增加views失败', error: err.message } 
            });
        }
        if (results.affectedRows !== 1) {
            return res.send({ 
                status: 400, 
                data: { message: '增加views失败，可能该文章不存在' } 
            });
        }
        res.send({
            status: 200,    
            message: '增加views成功',
            data: results
        });
    });
});
// 获取一个热门文章
router.get('/getHotArticle', (req, res) => {
    const sql = 'SELECT id,img,title,views FROM article ORDER BY views DESC LIMIT 1';
    db.query(sql, (err, results) => {
        if (err) {
            return res.send({ 
                status: 400, 
                data: { message: '查询热门文章失败', error: err.message } 
            });
        }
        if (results.length !== 1) {
            return res.send({ 
                status: 400, 
                data: { message: '查询热门文章失败，可能没有文章' } 
            });
        }
        
        // 将title字段改名为text返回给前端
        const result = results[0];
        const responseData = {
            id: result.id,
            img: result.img,
            text: result.title,  // 将title改名为text
            views: result.views
        };
        
        res.send({
            status: 200,    
            message: '查询热门文章成功',
            data: responseData
        });
    });
});


module.exports = router;